package com.qianyucc.blog.provider;

import com.alibaba.fastjson.*;
import com.qianyucc.blog.model.dto.*;
import lombok.extern.slf4j.*;
import me.zhyd.oauth.config.*;
import me.zhyd.oauth.model.*;
import me.zhyd.oauth.request.*;
import me.zhyd.oauth.utils.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

/**
 * @author lijing
 * @e-mail 1413979079@qq.com
 * @date 2020-05-14 20:48
 * @description QQ登录实现类
 */
@Component
@Slf4j
public class QQProvider {
    @Value("${qq.uri}")
    private String redirectUri;
    @Value("${qq.client.id}")
    private String clientId;
    @Value("${qq.client.secret}")
    private String clientSecret;
    private  AuthQqRequest authQqRequest;

    private  AuthRequest getAuthRequest() {
        if (authQqRequest == null) {
            authQqRequest = new AuthQqRequest(AuthConfig.builder()
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .redirectUri(redirectUri)
                    .build());
        }
        return authQqRequest;
    }
    /**
     * 获取用户信息
     *
     * @param callback 回调参数
     * @return 用户信息
     */
    public QQUserDTO getUserInfo(AuthCallback callback) {
        AuthResponse res = getAuthRequest().login(callback);
        if (res.ok()) {
            Object data = res.getData();
            String str = JSON.toJSONString(data);
            return JSON.parseObject(str, QQUserDTO.class);
        }
        return null;
    }

    /**
     * 获取登录地址
     *
     * @return 登录地址
     */
    public String getLoginUrl() {
        return getAuthRequest().authorize(AuthStateUtils.createState());
    }
}
